package com.pn.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.pn.entity.*;
import com.pn.exception.ProductDeleteException;
import com.pn.mapper.ProductMapper;
import com.pn.mapper.ProductTypeMapper;
import com.pn.service.ProductService;
import com.pn.utils.PageBean;
import com.pn.utils.Result;
import com.pn.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@CacheConfig(cacheNames = "com.pn.service.impl.ProductServiceImpl")
@Service
public class ProductServiceImpl implements ProductService {
    @Autowired
    private ProductMapper productMapper;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    //查询商品分类树
    @Cacheable(key = "'all:categoryTree'")
    @Override
    public List<ProductType> categoryTree() {

        List<ProductType> productTypes = productMapper.productTypeTree();
        List<ProductType> productTypeList = allcategoryTree(productTypes, 0);
        return productTypeList;
    }
    private List<ProductType> allcategoryTree(List<ProductType> allcategoryList,Integer pid){
        List<ProductType> firstCategoryList = new ArrayList<>();
        for (ProductType productType : allcategoryList) {
            if (productType.getParentId() == pid){
                firstCategoryList.add(productType);
            }
        }

        for (ProductType firstCategory : firstCategoryList) {
            List<ProductType> productTypes = allcategoryTree(allcategoryList, firstCategory.getTypeId());
            firstCategory.setChildProductCategory(productTypes);
        }
        return firstCategoryList;
    }

    //商品列表展示
    @Override
    public PageBean productPageList(Product product) {
        PageHelper.startPage(product.getPageNum(),product.getPageSize());
        Page<Product> page = productMapper.productPageList(product);
        return new PageBean(page.getTotal(),page.getResult());
    }

    //商品添加

    @Value("${file.access-path}")
    private String fileAccesPath;
    @Override
    public Result saveProduct(Product product) {
        //判断商品型号是否已存在
        Product prct = productMapper.findProductByNum(product.getProductNum());
        if (prct != null){
            return Result.err(Result.CODE_ERR_BUSINESS,"该型号的商品已存在");
        }
        //处理上传的图片的访问路径
        product.setImgs(fileAccesPath + product.getImgs());

        Map<String,Object> map =(Map<String, Object>) ThreadLocalUtil.get();
        Integer userId =(Integer) map.get("userId");
        product.setCreateBy(userId);
        product.setUpdateBy(userId);

        int i = productMapper.insertProduct(product);
        if (i > 0 ){
            return Result.ok("商品添加成功!");
        }
        return Result.err(Result.CODE_ERR_BUSINESS,"商品添加失败");
    }

    //商品上下架
    @Override
    public Result changeProductStateBId(Integer productId, String upDownState) {
        int i = productMapper.changeProductStateBId(productId,upDownState);
        if (i > 0 ){
            return Result.ok("商品上下架成功");
        }
        return Result.err(Result.CODE_ERR_BUSINESS,"商品上下架失败");
    }

    //删除一个或多个商品
    @Override
    public void deleteProductByIds(List<Integer> ids) {
        List<Product> products = productMapper.productSelectByIds(ids);
        //长度一样声明商品都是下架的状态
        if (products.size() == ids.size()){
            //执行删除语句
            productMapper.productRemoveByids(ids);
        }else{
            throw new ProductDeleteException("商品下架才能删除");
        }
    }

    //修改商品
    @Transactional
    @Override
    public Result productUpdate(Product product) {
        //先根据productId删除商品
        productMapper.deleteProductById(product.getProductId());
        //把传进来的名称改为id
        Integer brandId = productMapper.SelectBrandByName(product.getBrandName());
        product.setBrandId(brandId);
        Integer typeId = productMapper.SelectTypeByName(product.getTypeName());
        product.setTypeId(typeId);
        Integer supplyId = productMapper.SelectSupplyByName(product.getSupplyName());
        product.setSupplyId(supplyId);
        Integer placeId = productMapper.SelectPlaceByName(product.getPlaceName());
        product.setPlaceId(placeId);
        Integer unitId = productMapper.SelectUnitByName(product.getUnitName());
        product.setUnitId(unitId);
        Map<String,Object> map =(Map<String, Object>) ThreadLocalUtil.get();
        Integer userId =(Integer) map.get("userId");
        product.setUpdateBy(userId);
        //图片处理
        if (!product.getImgs().contains(fileAccesPath)){
            product.setImgs(fileAccesPath + product.getImgs());
        }

        //插入商品
        productMapper.insertProduct(product);
        return Result.ok("商品修改成功");
    }

    @Autowired
    private ProductTypeMapper productTypeMapper;
    //添加商品分类
    @CacheEvict(key = "'all:categoryTree'")
    @Override
    public Result saveProductType(ProductType productType) {

        //校验分类名称是否存在
        ProductType productType1 = new ProductType();
        productType1.setTypeName(productType.getTypeName());
        ProductType typeByCodeOrName = productTypeMapper.findTypeByCodeOrName(productType1);
        if (typeByCodeOrName != null){
            return Result.err(Result.CODE_ERR_BUSINESS,"分类名称已存在！");
        }

        int i = productTypeMapper.insertProductType(productType);
        if (i > 0 ){
            return Result.ok("添加商品分类成功！");
        }
        return Result.err(Result.CODE_ERR_BUSINESS,"添加商品分类失败！");
    }

    //删除商品分类
    @CacheEvict(key = "'all:categoryTree'")
    @Override
    public Result deleteTypeByTidOrPid(Integer typeId, Integer parentId) {
        int i = productMapper.deleteTypeByTidOrPid(typeId,parentId);
        if (i > 0){
            return Result.ok("删除商品分类成功！");
        }
        return Result.err(Result.CODE_ERR_BUSINESS,"删除商品分类失败！");
    }

    //修改商品分类
    @CacheEvict(key = "'all:categoryTree'")
    @Override
    public Result typeUpdate(ProductType productType) {
        ProductType type = new ProductType();
        type.setTypeName(productType.getTypeName());
        ProductType typeByCodeOrName = productTypeMapper.findTypeByCodeOrName(type);
        if (typeByCodeOrName != null && !typeByCodeOrName.getTypeId().equals(productType.getTypeId())){
            return Result.err(Result.CODE_ERR_BUSINESS,"分类名称已存在!");
        }

        int i = productMapper.typeUpdate(productType);
        if (i > 0){
            return Result.ok("修改商品分类成功！");
        }
        return Result.err(Result.CODE_ERR_BUSINESS,"修改商品分类失败！");
    }





}
